import winreg
import os
from common.reg_win import set_or_delete_local_machine
from common.utils import list_files, list_dir, unzip, make_zip
from common.enum import MyEnum, Runner


class WinAct(object):
    def __init__(self, env, config):
        self.env = env
        self.config = config

    @staticmethod
    def disable_defender():
        k = r"SOFTWARE\Policies\Microsoft\Windows Defender"
        set_or_delete_local_machine(k, "DisableAntiSpyware", 1, winreg.REG_DWORD)

    @staticmethod
    def disable_firewall():
        k = r"SYSTEM\CurrentControlSet\Services\MpsSvc"
        set_or_delete_local_machine(k, "Start", 4, winreg.REG_DWORD)

    @staticmethod
    def disable_error_reporting():
        k = r"SOFTWARE\Microsoft\Windows\Windows Error Reporting"
        set_or_delete_local_machine(k, "Disabled", 1, winreg.REG_DWORD)

    def install_pprogram(self):
        program_path = self.config.root_pprogram
        save_path = self.config.pprogram
        files = list_files(program_path)
        dirs = list_dir(save_path)
        for f in files:
            if f[-3:] != "zip":
                # filter zip file
                continue
            if f[:-4] in dirs:
                # do not overwrite
                continue
            unzip(save_path, f)

    def update_pprogram(self):
        program_path = self.config.root_pprogram
        source_path = self.config.pprogram
        dirs = list_dir(source_path, True)
        for d in dirs:
            files = list_files(d, True, True, MyEnum.ignore_pattern.value)
            save_name = program_path + "/" + os.path.basename(d) + ".zip"
            make_zip(save_name, files, source_path)

    @staticmethod
    def silent_install(program_path):
        cmd = "start /wait %s /S /v/qn" % program_path
        os.system(cmd)

    @staticmethod
    def step_install(program_path):
        cmd = "start %s" % program_path
        os.system(cmd)

    @staticmethod
    def active_vl_os():
        cmd = "slmgr /skms kms.03k.org"
        os.system(cmd)
        cmd = "slmgr /ato"
        os.system(cmd)

    def all_runner(self):
        defender = Runner("disable defender", self.disable_defender)
        firewall = Runner("disable firewall", self.disable_firewall)
        reporting = Runner("disable error reporting", self.disable_error_reporting)
        in_ = Runner("install portable program", self.install_pprogram)
        up_ = Runner("update portable program", self.update_pprogram)
        active_os = Runner("active vl os using kms in 03k.org", self.active_vl_os)
        runner_map = {
            MyEnum.restore_auto.value: [defender, firewall, reporting, in_, active_os],
            MyEnum.restore_all.value: [defender, firewall, reporting, in_, up_, active_os]
        }
        return runner_map




